package com.kele.demo.controller;

import com.kele.demo.entity.ToDoList;
import com.kele.demo.feign.AuthTokenFeign;
import com.kele.demo.service.impl.ToDoListServiceImpl;
import com.kele.framework.exception.utils.BadRequestException;
import com.kele.utils.RequestResult;
import com.kele.utils.RequestResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author chunhui.li
 * @date 2022/3/5 14:55
 * @Description
 * @ClassName ToDoListControllor
 */
@RestController
@RequestMapping("/todoList")
@CrossOrigin("*")
public class ToDoListControllor {

    @Autowired
    ToDoListServiceImpl toDoListService;

    @Autowired
    AuthTokenFeign authTokenFeign;

    @GetMapping("/getUserTodoList")
    public RequestResult getTodoListForUser(@RequestParam Long userId, HttpServletRequest request){

        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            return RequestResultUtil.error(403,"登陆过期请重新登陆");
        } else {
            Boolean aBoolean = authTokenFeign.checkToken(token);
            if (aBoolean){
                List<ToDoList> todoListForUser = toDoListService.getTodoListForUser(userId);
                return RequestResultUtil.success(todoListForUser);
            }
        }
        return RequestResultUtil.error(403,"登陆过期请重新登陆");
    }

    /**
     * 新增待办事项
     */
    @PostMapping("/addTodoList")
    public RequestResult addTodoList(@RequestBody ToDoList toDoList, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return RequestResultUtil.error(403, "登陆过期请重新登陆");
        } else {
            Boolean aBoolean = authTokenFeign.checkToken(token);
            if (aBoolean) {
                int result = toDoListService.addTodoList(toDoList);
                if (result > 0) {
                    return RequestResultUtil.success();
                }
            }
        }
        return RequestResultUtil.error(403, "登陆过期请重新登陆");
    }

    @RequestMapping("/test")
    public void test(){
        throw new BadRequestException("test");
    }
}
